<template>
    <div class="store">
        <el-card class="!border-none" shadow="never">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="门店名称">
                    <el-input
                        class="w-[280px]"
                        v-model="queryParams.name"
                        clearable
                        @keyup.enter="resetPage"
                    />
                </el-form-item>
                <el-form-item label="省市区">   
                    <el-cascader
                        size="large"
                        class="w-[280px]"
                        :options="pcaTextArr"
                        v-model="selectedQueryOptions"
                        @focus="clickQueryChange"
                        @change="handleQueryChange"
                    />
                </el-form-item>
                <!-- <el-form-item label="状态">
                    <el-select class="w-[280px]" v-model="queryParams.status" clearable>
                        <el-option label="启用" :value="1" />
                        <el-option label="禁用" :value="0" />
                    </el-select>
                </el-form-item> -->
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <div class="mb-4">
                <el-button type="primary" @click="handleAdd">新增门店</el-button>
            </div>

            <el-table size="large" v-loading="pager.loading" :data="pager.lists">
                <el-table-column label="门店名称" prop="name" min-width="120" />
                <el-table-column label="省份" prop="province" min-width="100" />
                <el-table-column label="城市" prop="city" min-width="100" />
                <el-table-column label="区县" prop="district" min-width="100" />
                <el-table-column label="详细地址" prop="address" min-width="200" show-overflow-tooltip />
                <el-table-column label="联系方式" prop="contactor" min-width="120" />
                <el-table-column label="状态" min-width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'info'">
                            {{ row.status === 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" min-width="180">
                    <template #default="{ row }">
                        {{ row.create_time > 0 ? timeFormat(row.create_time, 'YYYY-MM-DD HH:mm:ss') : '' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                        <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>

        <!-- 新增/编辑弹窗 -->
        <el-dialog
            v-model="formDialog.show"
            :title="formDialog.form.id > 0 ? '编辑门店' : '新增门店'"
            width="550px"
            @close="formDialog.show = false"
        >
            <el-form
                ref="dialogFormRef"
                :model="formDialog.form"
                :rules="formDialog.rules"
                label-width="100px"
            >
                <el-form-item label="门店名称" prop="name">
                    <el-input v-model="formDialog.form.name" placeholder="请输入门店名称" />
                </el-form-item>
                <el-form-item prop="area">
                    <template #label><span style="color: var(--el-color-danger);margin-right: 2px;">*</span>所在地区</template>
                    <el-cascader
                        size="large"
                        class="w-full"
                        :options="pcaTextArr"
                        v-model="selectedOptions"
                        @change="handleChange"
                        :teleported="false"
                    >
                    </el-cascader>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model="formDialog.form.address" placeholder="请输入详细地址" />
                </el-form-item>
                <el-form-item label="联系方式" prop="contactor">
                    <el-input v-model="formDialog.form.contactor" maxlength="11" placeholder="请输入联系方式" />
                </el-form-item>
                <el-form-item label="经度" prop="longitude">
                    <el-input v-model="formDialog.form.longitude" maxlength="10" placeholder="请输入经度" />
                </el-form-item>
                <el-form-item label="纬度" prop="latitude">
                    <el-input v-model="formDialog.form.latitude" maxlength="9" placeholder="请输入纬度" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="formDialog.form.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="formDialog.show = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="store">
import { storeLists, storeCreate, storeUpdate, storeDelete } from '@/api/store'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import { timeFormat } from '@/utils/util'
import { pcaTextArr } from "element-china-area-data";
const queryParams = reactive({
    name: '',
    province: '',
    city: '',
    district: '',
})

const selectedOptions = ref([])
const selectedQueryOptions = ref([])

const handleQueryChange = (value: any) => {
    selectedQueryOptions.value = value
    queryParams.province = value[0]
    queryParams.city = value[1]
    queryParams.district = value[2]
}

const clickQueryChange = (value: any) => {
    console.log(value)
    if(selectedQueryOptions.value.length === 0){
        selectedQueryOptions.value = [
            "福建省" as never,
            "厦门市" as never,
            "思明区" as never
        ]
    }
}

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: storeLists,
    params: queryParams
})

// 表单弹窗数据
const formDialog = reactive({
    show: false,
    form: {
        id: 0,
        name: '',
        province: '',
        city: '',
        district: '',
        address: '',
        contactor: '',
        longitude: '',
        latitude: '',
        status: 1
    },
    rules: {
        name: [{ required: true, message: '请输入门店名称' }],
        province: [{ required: true, message: '请选选择省份' }],
        city: [{ required: true, message: '请选选择城市' }],
        district: [{ required: true, message: '请选选择区县' }],
        address: [{ required: true, message: '请输入详细地址' }],
        contactor: [
            { required: true, message: '请输入联系方式' },
            { pattern: /^\d{11}$/, message: '请输入11位手机号码' },
        ],
        longitude: [
            { required: true, message: '请输入经度' },
            { pattern: /^-?\d+(\.\d{0,6})?$/, message: '请输入正确的经度格式，最多6位小数' },
            { validator: (rule: any, value: any, callback: any) => {
                const num = Number(value)
                if (isNaN(num) || num < -180 || num > 180) {
                    callback(new Error('经度范围必须在-180到180度之间'))
                } else {
                    callback()
                }
            }}
        ],
        latitude: [
            { required: true, message: '请输入纬度' },
            { pattern: /^-?\d+(\.\d{0,6})?$/, message: '请输入正确的纬度格式，最多6位小数' },
            { validator: (rule: any, value: any, callback: any) => {
                const num = Number(value)
                if (isNaN(num) || num < -90 || num > 90) {
                    callback(new Error('纬度范围必须在-90到90度之间'))
                } else {
                    callback()
                }
            }}
        ]
    }
})

const dialogFormRef = ref()

// 打开新增弹窗
const handleAdd = () => {
    dialogFormRef.value?.resetFields()
    selectedOptions.value = [
        "福建省" as never,
        "厦门市" as never,
        "思明区" as never
    ]
    formDialog.show = true
}

// 打开编辑弹窗
const handleEdit = (row: any) => {
    formDialog.form = {
        ...row
    }
    selectedOptions.value = [
        formDialog.form.province as never,
        formDialog.form.city as never,
        formDialog.form.district as never
    ]
    formDialog.show = true
}

// 提交表单
const submitForm = async () => {
    await dialogFormRef.value?.validate()
    const params = { ...formDialog.form,
        longitude:Number(formDialog.form.longitude),
        latitude:Number(formDialog.form.latitude),
        province:selectedOptions.value[0],
        city:selectedOptions.value[1],
        district:selectedOptions.value[2]
    }
    if (params.id === 0) {
        await storeCreate(params)
    } else {
        await storeUpdate(params)
    }
    feedback.msgSuccess('操作成功')
    formDialog.show = false
    getLists()
}

// 删除
const handleDelete = async (row: any) => {
    await feedback.confirm('确认删除该门店？')
    await storeDelete({ id: row.id })
    feedback.msgSuccess('删除成功')
    getLists()
}

const handleChange = (value: any) => {
    selectedOptions.value = value
    formDialog.form.province = value[0]
    formDialog.form.city = value[1]
    formDialog.form.district = value[2]
}

onActivated(() => {
    getLists()
})

getLists()
</script>